package com.jeffmony.sample;


import android.text.TextUtils;
import android.util.Log;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

public class SocketClient {


    private static String TAG = "SocketClient";

    /**
     * 错误消息
     * */
    private final static String HOST_OR_PROT_NULL = "socket连接信息不正确，ip: %s，port: %d";
    private final static String SOCKET_NOT_RESPONSE = "socket服务无响应数据，ip: %s，port: %d";
    private final static String SOCKET_LINK_FAIL = "socket连接失败，请检查相应socket服务是否已开启，ip: %s，port: %d";
    private final static String SOCKET_TIMEOUT = "socket请求超时，ip: %s，port: %d";
    private final static String SOCKET_EXCEPTION = "socket请求IO异常，ip: %s，port: %d";

    /**
     * socket请求
     * @return
     */
    public static SocketResponseDTO request(String host, int port) {
        return request(host, port, null);
    }

    /**
     * socket请求
     * @param host ip
     * @param port 端口
     * @param param 请求参数
     * @return
     */
    public static SocketResponseDTO request(String host, int port, String param) {
        SocketResponseDTO socketResponse = new SocketResponseDTO();
        if (TextUtils.isEmpty(host) || Objects.isNull(port)) {
//            socketResponse.setErrorMsg(String.format(HOST_OR_PROT_NULL, host, port));
            return socketResponse;
        }
        try (
                // 与服务端建立连接
                Socket socket = new Socket(host, port);
                // 输出数据流
                OutputStream socketOutputStream = socket.getOutputStream();
                // 输入数据流

        ){
            // 60s超时
            socket.setSoTimeout(60000);
//            String method = "GET";
//            socketOutputStream.write(method.getBytes(StandardCharsets.UTF_8));
            if (Objects.nonNull(param)) {
                // 建立连接后获得输出流，发送数据
                socketOutputStream.write(param.getBytes(StandardCharsets.UTF_8));
            }
            // 通过shutdownOutput 告诉接收端已经发送完数据，客户端后续只能接受数据
            socket.shutdownOutput();
            //读取服务器返回的消息
            InputStream socketInputStream = socket.getInputStream();

            if (socketInputStream != null) {
                int readIndex;
                byte[] bytes = new byte[1024 * 16];
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                while ((readIndex = socketInputStream.read(bytes)) > -1) {
                    byteArrayOutputStream.write(bytes, 0, readIndex);
//                    Log.d(TAG,"byteArrayOutputStream" + readIndex);
                }
                byte[] buff=byteArrayOutputStream.toByteArray();
                String str = new String(buff);
//                socketResponse.setResponse(byteArrayOutputStream.toByteArray());
                Log.d(TAG,"byteArrayOutputStream" + str);

            } else {
//                socketResponse.setErrorMsg(String.format(SOCKET_NOT_RESPONSE, host, port));
            }
        } catch (ConnectException e) {
//            socketResponse.setErrorMsg(String.format(SOCKET_LINK_FAIL, host, port));
//            Log.e(socketResponse.getErrorMsg(), e.toString());
        } catch (SocketTimeoutException e) {
//            socketResponse.setErrorMsg(String.format(SOCKET_TIMEOUT, host, port));
//            Log.e(socketResponse.getErrorMsg(), e.toString());
        } catch (IOException e) {
//            socketResponse.setErrorMsg(String.format(SOCKET_EXCEPTION, host, port));
//            Log.e(socketResponse.getErrorMsg(), e.toString());
        }
        return socketResponse;
    }
}